package com.iqiyi.pps.epg.core.utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Des3EncryptUtils {

	public static final String CHAR_ENCODING = "UTF-8";

	public static String encode(String key, String data) {
		try {
			byte[] keyByte = key.getBytes(CHAR_ENCODING);
			byte[] dataByte = data.getBytes(CHAR_ENCODING);
			byte[] valueByte = des3Encryption(
					keyByte, dataByte);                   // , CHAR_ENCODING
			String value = new String(Base64.encode(valueByte));
			return value;
		} catch (Exception e) {
			return null;
		}
	}

	public static String decode(String key, String value){
		try {
			byte[] keyByte = key.getBytes(CHAR_ENCODING);    // .getBytes(CHAR_ENCODING)
			byte[] valueByte = Base64.decode(value);
			byte[] dataByte = des3Decryption(keyByte,
					valueByte);
			String data = new String(dataByte, CHAR_ENCODING);
			return data;
		} catch (Exception e) {
			return null;
		}
	}

	 /**
	   * 字符串 DESede(3DES) 加密
	   * @param key - 为24字节的密钥（3组x8字节）
	   * @param data - 需要进行加密的数据（8字节）
	   * @return
	   */
	  public static byte[] des3Encryption(byte[] key, byte[] data) throws
              NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
              BadPaddingException, IllegalBlockSizeException, IllegalStateException {
	    final String Algorithm = "DESede"; // 定义 加密算法,可用 DES,DESede,Blowfish

	    //生成密钥
	    SecretKey deskey = new SecretKeySpec(key, Algorithm);

	    //加密
	    Cipher c1 = Cipher.getInstance(Algorithm);
	    c1.init(Cipher.ENCRYPT_MODE, deskey);
	    return c1.doFinal(data);
	  }

	  /**
	   * 字符串 DESede(3DES) 解密
	   * @param key - 为24字节的密钥（3组x8字节）
	   * @param data - 需要进行解密的数据（8字节）
	   * @return
	   */
	  public static byte[] des3Decryption(byte[] key, byte[] data) throws
              NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
              BadPaddingException, IllegalBlockSizeException, IllegalStateException {
	    final String Algorithm = "DESede"; // 定义 加密算法,可用 DES,DESede,Blowfish

	    //生成密钥
	    SecretKey deskey = new SecretKeySpec(key, Algorithm);

	    //加密
	    Cipher c1 = Cipher.getInstance(Algorithm);
	    c1.init(Cipher.DECRYPT_MODE, deskey);
	    return c1.doFinal(data);
	  }

	  public static void main(String[] args){
		  //商户后台设置的密钥 36位
		  String key ="111111111111111111111118111111111111";
		  String data="ICBC";
		  //取密钥的前24位
		  key = key.substring(0, 24);
		  System.out.println(key);
		  //加密
		  String str = encode(key, data);
		  System.out.println(str);
		  //解密
		  String dtr = decode(key,str);
		  System.out.println(dtr);
	  }



}